#!/usr/bin/env python3

import argparse
import hashlib
import json
import pathlib
import re
import shlex
import shutil
import subprocess
import sys
import tomllib
import urllib.request


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Update the versions.json and nix dependencies",
    )
    parser.add_argument(
        "--nix",
        action=argparse.BooleanOptionalAction,
        default=True,
        help="update nix dependencies by running `npins update` (default: yes)",
    )
    parser.add_argument(
        "--nightly",
        type=str,
        help="nightly version, e.g. 2021-01-01 (default: use latest)",
    )
    parser.add_argument(
        "--stable",
        type=str,
        help="stable version, e.g. 1.76.0 (default: use latest)",
    )
    args = parser.parse_args()

    if args.nix:
        if shutil.which("npins") is not None:
            command = ["npins", "update"]
        else:
            command = ["nix-shell", "-p", "npins", "--run", "npins update"]
        print(f"Running {shlex.join(command)}", file=sys.stderr)
        subprocess.run(
            args=command,
            cwd=pathlib.Path(__file__).parent,
            check=True,
        )

    print("Updating versions.json", file=sys.stderr)
    d = f"{args.nightly}/" if args.nightly else ""
    url = f"https://static.rust-lang.org/dist/{d}channel-rust-nightly.toml"
    with urllib.request.urlopen(url) as response:
        data = response.read()
    nightly_sha256 = hashlib.sha256(data).digest().hex()
    nightly_date = tomllib.loads(data.decode("utf-8"))["date"]

    d = args.stable if args.stable else "stable"
    url = f"https://static.rust-lang.org/dist/channel-rust-{d}.toml"
    with urllib.request.urlopen(url) as response:
        data = response.read()
    stable_sha256 = hashlib.sha256(data).digest().hex()
    stable_version = tomllib.loads(data.decode("utf-8"))["pkg"]["rust"]["version"]
    m = re.match(r"^(\d+\.\d+\.\d+) \(.*\)$", stable_version)
    if not m:
        raise ValueError(f"Failed to parse stable version: {stable_version}")
    stable_version = m[1]

    result = {
        "#": "This file is autogenerated by ./update.py",
        "nightly": {
            "date": nightly_date,
            "sha256": nightly_sha256,
        },
        "stable": {
            "version": stable_version,
            "sha256": stable_sha256,
        },
    }

    with open(pathlib.Path(__file__).parent / "versions.json", "w") as f:
        f.write(json.dumps(result, indent=2) + "\n")


if __name__ == "__main__":
    main()
